package kosta.controller;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import kosta.model.vo.AuctionVO;
import kosta.model.vo.BidVO;
import kosta.model.vo.BigClassVO;
import kosta.model.vo.DeleteConfirmVO;
import kosta.model.vo.ListVO;
import kosta.model.vo.MemberVO;
import kosta.model.vo.SearchVO;
import kosta.model.vo.SmallClassVO;
import kosta.service.AuctionService;
import kosta.service.MemberService;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/auction")
public class AuctionController {
	@Resource(name="uploadPath")
	private String path;
	@Resource(name="auctionServiceImpl")
	private AuctionService auctionService;
	@Resource(name="memberServiceImpl")
	private MemberService memberService;
	
	@RequestMapping("/{viewId}View.do")
	public String showView(@PathVariable("viewId") String viewId){
		//System.out.println(viewId);
		return viewId+"View.auction";
	}
	
	@RequestMapping("/endCountDown.do")
	@ResponseBody
	   public String endCountDown(AuctionVO avo,HttpServletRequest request){
	      List<BidVO> list=auctionService.bid(avo.getBoardNo());
	       if(list.size()==0){
	          avo.setInactiveReason("종료");
	      }else{
	         avo.setInactiveReason("낙찰");
	      }
	      auctionService.endBid(avo);
	      return "endCountDown";
	   }
	
	
	//키워드로 검색
	@RequestMapping("/findByKeyword.do")	
	public ModelAndView findByKeyword(HttpServletRequest request,
			HttpServletResponse response, SearchVO svo){	
		String keyword = request.getParameter("keyword");
		String pageNo=request.getParameter("pageNo");	
		System.out.println("키워드랑 페이지넘버"+keyword+pageNo);
		ListVO alvo = auctionService.findByKeyword(svo);			
			
		System.out.println("alvo : "+alvo);
		return new ModelAndView("findAuctionBoard.auction","lvo",alvo);
	
	}
	
	
	
	//게시물 등록
	@RequestMapping("/auth_auctionRegister.do")	
	public String auctionRegister(HttpServletRequest request,
			HttpServletResponse response, AuctionVO avo){
		//System.out.println("fileUpload"+vo);
		MultipartFile mFile=avo.getUploadFile();
		//System.out.println("isEmpty()"+mFile.isEmpty());
		if(mFile!=null&&!mFile.isEmpty()){
			//System.out.println(path+" "+mFile.getOriginalFilename());
			File copyFile=new File(path+mFile.getOriginalFilename());
			avo.setAttatchedFile(mFile.getOriginalFilename());
			try {
				mFile.transferTo(copyFile);
				System.out.println("file upload ok~~");
			} catch (IllegalStateException | IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
		System.out.println("auctionRegister "+avo);
		auctionService.auctionRegister(avo);		
		return "redirect:auth_auctionRegisterResult.do?smallClassNo="+avo.getSmallClassNo();
		
	}
	
	//게시판 보여주기
	@RequestMapping("/auth_auctionRegisterResult.do")	
	public ModelAndView auctionRegisterView(HttpServletRequest request,
			HttpServletResponse response, SearchVO svo){	
		System.out.println("auctionRegisterView "+svo);		
		ListVO lvo =auctionService.getAuctionList(svo);
		return new ModelAndView("findAuctionBoard.auction","lvo",lvo);
		
	}
	
	//실제 게시물 업데이트
	@RequestMapping("/auctionUpdate.do")
	public String auctionUpdate (HttpServletRequest request,
	         HttpServletResponse response,AuctionVO avo){   
		System.out.println("~업데이트 부분~");
		System.out.println("auctionUpdate : "+avo);
	     auctionService.auctionUpdate(avo);	         
	      return "redirect:showContentNotHit.do?boardNo="+avo.getBoardNo();
	}
	
	//게시물 업데이트 후 결과 보여주기
	@RequestMapping("/auth_auctionUpdateResult.do")
	public ModelAndView auctionUpdateResult (HttpServletRequest request,
	         HttpServletResponse response,SearchVO svo){   
		System.out.println("auctionUpdateView "+svo);		
		ListVO lvo =auctionService.getAuctionList(svo);
		return new ModelAndView("findAuctionBoard.auction","lvo",lvo);
	}
	//대분류 받아오기.
	@RequestMapping("/findByCategory.do")
	@ResponseBody
	public List<BigClassVO> getBigClassList(HttpServletRequest request,
			HttpServletResponse response){		
		List<BigClassVO>  list = auctionService.getBigClassList();
		System.out.println("getBigClassList 대분류 리스트 : "+list);
		return list;
	}	
	

	
	
	//소분류 받아오기.
	@RequestMapping("/getSmallClassList.do")
	@ResponseBody
	public List<SmallClassVO> getSmallClassList(HttpServletRequest request,
			HttpServletResponse response){	
		int bigClass = Integer.parseInt(request.getParameter("bigClass"));
		List<SmallClassVO> smallClasslist = auctionService.getSmallClassList(bigClass);
		System.out.println("소분류 리스트 : "+smallClasslist);
		return smallClasslist;
	}
	//소분류로 상품 검색.
	@RequestMapping("/findBySmallClass.do")
	public ModelAndView findBySmallClass(HttpServletRequest request,
			HttpServletResponse response, SearchVO svo){	
		System.out.println(svo);
		ListVO lvo = auctionService.findBySmallClass(svo);
		System.out.println("소분류로 검색한 리스트 : "+lvo);
		 return new ModelAndView("findAuctionBoard.auction","lvo",lvo);
	}
	
	
	
	@RequestMapping("/auth_buybid.do")
	@ResponseBody
	public String buyBid(BidVO bvo, AuctionVO avo, HttpServletRequest request){
		HttpSession session = request.getSession(false);
		MemberVO mvo = (MemberVO) session.getAttribute("mvo");
		System.out.println("현재 세션에 있는 아이디 : "+mvo.getMemberId());
		bvo.setSellerId(mvo.getMemberId());
		System.out.println("레지스터전"+bvo);
		auctionService.BidRegister(bvo);
		avo.setInactiveReason("낙찰");
		System.out.println("param bvo값 : "+bvo);
		System.out.println("param avo값 : "+avo);
		auctionService.endBid(avo);
		return "end";
	}
	
	//show Content의 입찰내역을 보여줌
	   @RequestMapping("/bid.do")
	   @ResponseBody
	   public HashMap bidRegister(BidVO bvo, HttpServletRequest request){
	      HashMap map=new HashMap();
	      HttpSession session = request.getSession(false);
	      MemberVO mvo = (MemberVO) session.getAttribute("mvo");
	      List<BidVO> bdvo=auctionService.bid(bvo.getBoardNo());
	      bvo.setSellerId(mvo.getMemberId());
	      if(bdvo.size()==0){
		       auctionService.BidRegister(bvo);
		       map.put("result", "O");
	      }else{
	    	  String priceCheck=auctionService.priceCheck(bvo);    	  
		      int minPrice=auctionService.minbidPrice(bvo.getBoardNo());
		      if(minPrice<bvo.getBidPrice()){
		         map.put("minPriceResult", "N");
		      }else{
		    	 if(priceCheck==null){
				     map.put("result", "O");
				     auctionService.BidRegister(bvo);
				 }else{
				    map.put("result", "X");
				 }
		      }
	      }
	      return map;
	   }
		
	@RequestMapping("/auth_deleteConfirm.do")
	@ResponseBody
	public String deleteConfirm(DeleteConfirmVO dcvo,AuctionVO avo, HttpServletRequest request){
		String ch=null;	
		avo.setInactiveReason("삭제요청");
		DeleteConfirmVO dc=auctionService.findDelConfirm(dcvo.getBoardNo());
		if(dc==null){
			auctionService.deleteConfirm(dcvo);
			auctionService.endBid(avo);
			ch="delCon";
		}else{
			ch="delFail";
		}
		return ch;
	}
	
	@RequestMapping("/showContentNotHit.do")
	public ModelAndView showContentNotHit(HttpServletRequest request,
			HttpServletResponse response) throws ParseException{
			int boardNo=Integer.parseInt(request.getParameter("boardNo"));	
			AuctionVO avo=auctionService.findAuctionInfoNotHit(boardNo);			
			SimpleDateFormat sdformat=new SimpleDateFormat("yyyy-mm-dd HH:mm:ss"); 
	        Date date=sdformat.parse(avo.getTimePosted());
	        System.out.println("data : "+date);
	        // 포맷변경 ( 년월일 시분초)
	        // Java 시간 더하기
	        Calendar cal = Calendar.getInstance();
	        //cal에 게시물등록시간 추가.
	        cal.setTime(date);	        
	        cal.add(Calendar.HOUR, Integer.parseInt(avo.getAuctionTime()));
	        avo.setAuctionTime(sdformat.format(cal.getTime()));	        
	       /* cal.setTime(date);*/			
			MemberVO mvo=auctionService.findMemberInfo(avo.getMemberNo());
			SmallClassVO scvo=auctionService.findSmallClass(avo.getBoardNo());
			List<BidVO> bdvo=auctionService.bid(boardNo);
			BigClassVO bcvo=auctionService.findBigClass(scvo.getBigClassNo());
			HashMap map=new HashMap();
			map.put("avo", avo);
			map.put("mvo",mvo);
			map.put("scvo", scvo);
			map.put("bcvo", bcvo);
			map.put("bdvo",bdvo);
			return new ModelAndView("showContent.auction","vo",map);
	}		
		
		
	
	//showContent의 상세정보를 보여줌
	@RequestMapping("/showContent.do")
	public ModelAndView showContent(HttpServletRequest request,
			HttpServletResponse response) throws ParseException{

		int boardNo=Integer.parseInt(request.getParameter("boardNo"));
		AuctionVO avo=null;
		
		Cookie[] cookies=request.getCookies();		
		if(cookies==null || cookies.length==0){
			System.out.println ("1.쿠키가 존재하지 않은 상태..myboard cookie 전송");
			response.addCookie(new Cookie("myboard","|"+boardNo+"|"));
			//조회수 증가 			
			avo=auctionService.findAuctionInfo(boardNo);
		}else{
			Cookie myboardCookie=null;
			for(int i=0;i<cookies.length;i++){
				if(cookies[i].getName().equals("myboard")){
					myboardCookie=cookies[i];
					break;
				}
			}
			if(myboardCookie==null){
				System.out.println ("2.쿠키가 존재하지만 myboard 쿠키가 존재하지 않은 상태..myboard cookie 전송");
				response.addCookie(new Cookie("myboard","|"+boardNo+"|"));
				//조회수 증가 				
				avo=auctionService.findAuctionInfo(boardNo);
			}else{
				System.out.println ("3.쿠키가 존재하고 myboard 쿠키가 존재하는 상태..");
				String value=myboardCookie.getValue();
				if(value.indexOf("|"+boardNo+"|")!=-1){
					System.out.println ("3.1 해당 게시글 번호가 존재..조회수 증가하지 않는다");
					//조회수 증가 X
					//vo=boardService.getPostingByNoNotHit(no);				
					avo=auctionService.findAuctionInfoNotHit(boardNo);
					
				}else{// -1 즉 존재하지 않으면 
					System.out.println ("3.2 해당 게시글 번호가 존재X..조회수 증가하고 value업데이트 후 전송");
					value+="|"+boardNo+"|";
					response.addCookie(new Cookie("myboard",value));
					//조회수 증가 
					avo=auctionService.findAuctionInfo(boardNo);				
				}
			}
		}		
		
		
        
       /* cal.setTime(date);*/
		
		MemberVO mvo=auctionService.findMemberInfo(avo.getMemberNo());
		SmallClassVO scvo=auctionService.findSmallClass(avo.getBoardNo());
		List<BidVO> bdvo=auctionService.bid(boardNo);
		BigClassVO bcvo=auctionService.findBigClass(scvo.getBigClassNo());
		HashMap map=new HashMap();
		map.put("avo", avo);
		map.put("mvo",mvo);
		map.put("scvo", scvo);
		map.put("bcvo", bcvo);
		map.put("bdvo",bdvo);
		
		return new ModelAndView("showContent.auction","vo",map);
	}
	
	@RequestMapping("/auth_auctionUpdateForm.do")
	   public ModelAndView auctionUpdateForm(HttpServletRequest  request){
	      int boardNo=Integer.parseInt(request.getParameter("boardNo"));
	      AuctionVO avo=auctionService.findAuctionInfo(boardNo);
	      MemberVO mvo=auctionService.findMemberInfo(avo.getMemberNo());
	      SmallClassVO scvo=auctionService.findSmallClass(avo.getBoardNo());
	      BigClassVO bcvo=auctionService.findBigClass(scvo.getBigClassNo());
	      HashMap map=new HashMap();
	      map.put("avo", avo);
	      System.out.println("avo"+avo);
	      map.put("mvo",mvo);
	      System.out.println("mvo"+mvo);
	      map.put("scvo", scvo);
	      System.out.println("scvo"+scvo);
	      map.put("bcvo", bcvo);
	      System.out.println("bcvo"+bcvo);
	      return new ModelAndView("auctionUpdateForm.auction","vo",map);
	   }
	
}
